<template>
  <div class="load" ref="loadingRef">
    <div class="load-item"  v-loading="state.loading"></div>
  </div>
</template>

<script setup>
import {onBeforeUnmount, onMounted, reactive, ref} from "vue";
const emit = defineEmits(['load'])
const loadingRef = ref()

const state = reactive({
  loading:false,
  observer:null
})
onMounted(()=>{
  state.observer = new IntersectionObserver(
      ([{ isIntersecting }]) => {
        // 目标元素与根元素相交
        if (isIntersecting) {
          state.loading = true
          emit('load')
          state.loading = false
        }
      },
      {
        threshold: 1 // 相交距离
      }
  )
  // 观察目标元素
  state.observer.observe(loadingRef.value)
})

onBeforeUnmount(() => {
  state.observer.disconnect()
})
</script>

<style scoped lang="less">
.load{
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  .load-item{
    width: 60px;
    height: 60px;
  }
}
</style>